// ---------------------------------------------------------------------
//
// -- 通用信息
// -- author £
//
// ---------------------------------------------------------------------

const CommonUtil = require('CommonUtil'),
    AppInfo = require('AppInfo');

const DATA_KEY = 'HexagonDFTTCommon',
    LOGIN_INVALID_TIME = 604800000;

const REQUIRE_REGIST_STR = '该功能需要您同意授权用户信息。'

let CommonInfo = {
    comonData: null,

    // /** 当前配置选项 */
    // curRuleData: null,
    /** 场景状态 0 大厅 1 游戏 */
    sceneState: 0,
    showResult: false,
    bestScore: 0,
    dayBestScore: 0,

    roomOwner: false,
    gameUrl: '',
    loginUrl: 'wss://wxgamelogin.leshu.com',
    record: -1,
    golds: 0,
    diamonds: 0,
    /** 玩家信息 */
    userInfo: {},
    userRegisted: false,
    items: {},
    totalRCoin: 5,
    shareRCoinCount: 0,
    shareRCoinId: 0,
    rCoinId: 1001,
    // curGameID: 0,
    seatNum: 0,
    players: [],

    /** 启动 */
    startup: function () {
        this.comonData = cc.sys.localStorage.getItem(DATA_KEY);

        if (!this.comonData) {
            this.comonData = {
                recentHeads: [
                    'http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83epIEMXQP0ctfqs7qshBtzsdaicLuyRnKjU8MNuceRfb0m1JnzXYf7FttroOibQVPIa74vsAVyhHwLdA/132',
                    'http://thirdwx.qlogo.cn/mmopen/vi_32/W5Zpc55IzvjxIIqk7FITzjFsJQwVJHibfianFZyGZ9c0WjCHuU7cD1zVC0VqWc0OfQqGicMMPSKKMXR9s49JFXq4A/132',
                    'http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJGlLQiaOKYddNcgOV1DJnAqlE2l4yQJEgY69mNiaWGs1leRaa6ibqJjY6fbJYUAflVralLiaSnRgtw0g/132',
                    'http://thirdwx.qlogo.cn/mmopen/vi_32/q4picvTRkIRltNk30eMwqB1vcEDn735Fo3yKPRVmQ3SSPIDBSJpEmbh21bvwnyicRHP2gIeGBibAj6oia25nSrvkXQ/132',
                    'http://thirdwx.qlogo.cn/mmopen/vi_32/JaQ6R1ibCBvMUJkMcrYAo6fFef9Bx5OUVlbWN3T5a6XBWcS4M1XgGZ735U8BLK0PZ11M4Wk8omVREO7t0UEdUicA/132',
                    'http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLXjDZnlYfk695UFPKEF1SZ1d2WZW1YnqaEtJuhZJ5oav9dunAJibLCOR3LKhWL5iabpOYrdbyqqHwQ/132'
                ],
                teched: false,
                myBest: [],
            };
        } else {
            this.comonData = JSON.parse(this.comonData);

            if (this.comonData.recentHeads === undefined)
                this.comonData.recentHeads = [
                    'http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83epIEMXQP0ctfqs7qshBtzsdaicLuyRnKjU8MNuceRfb0m1JnzXYf7FttroOibQVPIa74vsAVyhHwLdA/132',
                    'http://thirdwx.qlogo.cn/mmopen/vi_32/W5Zpc55IzvjxIIqk7FITzjFsJQwVJHibfianFZyGZ9c0WjCHuU7cD1zVC0VqWc0OfQqGicMMPSKKMXR9s49JFXq4A/132',
                    'http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJGlLQiaOKYddNcgOV1DJnAqlE2l4yQJEgY69mNiaWGs1leRaa6ibqJjY6fbJYUAflVralLiaSnRgtw0g/132',
                    'http://thirdwx.qlogo.cn/mmopen/vi_32/q4picvTRkIRltNk30eMwqB1vcEDn735Fo3yKPRVmQ3SSPIDBSJpEmbh21bvwnyicRHP2gIeGBibAj6oia25nSrvkXQ/132',
                    'http://thirdwx.qlogo.cn/mmopen/vi_32/JaQ6R1ibCBvMUJkMcrYAo6fFef9Bx5OUVlbWN3T5a6XBWcS4M1XgGZ735U8BLK0PZ11M4Wk8omVREO7t0UEdUicA/132',
                    'http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLXjDZnlYfk695UFPKEF1SZ1d2WZW1YnqaEtJuhZJ5oav9dunAJibLCOR3LKhWL5iabpOYrdbyqqHwQ/132'
                ];

            if (this.comonData.myBest === undefined)
                this.comonData.myBest = [];
        }

        this.saveData();
    },

    setCurScore: function (score) {
        this.bestScore = score;

        if (this.dayBestScore < score)
            this.dayBestScore = score;

        this.updateMyBest(score);
    },

    updateMyBest: function (score) {
        let list = this.comonData.myBest, len = list.length,
            find = false, item, date = new Date(), time, i;

        date.setMilliseconds(0);
        date.setSeconds(0);
        date.setMinutes(0);
        date.setHours(0);
        time = date.getTime();

        for (i = 0; i < len; ++i) {
            item = list[i];
            
            if (item.date === time) {
                if (score > item.score)
                    item.score = score;

                find = true;
                break;
            }
        }

        if (!find) {
            let bInsert = false, 
                insertItem = {score: score, date: time};

            for (i = 0; i < len; ++i) {
                item = list[i];

                if (time > item.date) {
                    list.splice(i, 0, insertItem);
                    break;
                } 
            }

            if (!bInsert) {
                list[list.length] = insertItem;
            }

            if (list.length > 14) {
                list.length = 14;
            }
        }

        console.log('update mybest list:', this.comonData.myBest);
        this.saveData();
    },

    /** 获取自己的历史成绩 */
    getMyBest: function () {
        return this.comonData.myBest;
    },

    /** 设置复活币数据 */
    setRCoinData: function (data) {
        let itemInfo = data.item_reward.split(':');

        this.rCoinId = itemInfo[0];
        this.shareRCoinCount = itemInfo[1];
        this.shareRCoinId = data.share_id;
        require('GameText').shareReviveTxt = data.content;
        require('GameConfig').rCoinImgUrl = data.img;
    },

    /** 设置道具 */
    setUserItems: function (data) {
        if (!data.items) return;

        let itemArr = data.items.split(','), k, v, tmp;

        this.items = {};

        for (let i = 0; i < itemArr.length; ++i) {
            tmp = itemArr[i].split(':');
            k = tmp[0];
            v = parseInt(tmp[1]);
            this.items[k] = v;
        }
    },

    /** 获取某一道具的数量 */
    getItemCount: function (itemId) {
        console.log('get item count, itemId:', itemId);
        if (!this.items[itemId])
            this.items[itemId] = 0;
        console.log('item count:', this.items[itemId]);
        return this.items[itemId];
    },

    /** 获取复活币的数量 */
    getRCoinNum: function () {
        return this.getItemCount(this.rCoinId);
    },

    /** 设置复活币的数量 */
    updateRCoinNum: function (d) {
        if (this.items[this.rCoinId] === undefined ||
            this.items[this.rCoinId] === null) return;

        this.items[this.rCoinId] += d;

        if (this.items[this.rCoinId] > this.totalRCoin)
            this.items[this.rCoinId] = this.totalRCoin;
        else if (this.items[this.rCoinId] < 0)
            this.items[this.rCoinId] = 0;
    },

    /** 设置微信数据 */
    setWXUserInfo: function (userInfo) {
        console.log('setWXUserInfo:', userInfo);
        this.userRegisted = true;
        this.userInfo.nickname = userInfo.nickName;
        this.userInfo.headimgurl = userInfo.avatarUrl;
        this.userInfo.sex = userInfo.gender;
        this.userInfo.province = userInfo.province;
        this.userInfo.city = userInfo.city;

        if (!this.comonData.cacheUserInfo)
            this.comonData.cacheUserInfo = {};

        let cu = this.comonData.cacheUserInfo;

        cu.nickname = userInfo.nickName;
        cu.headimgurl = userInfo.avatarUrl;
        cu.sex = userInfo.gender;
        cu.province = userInfo.province;
        cu.city = userInfo.city;
        this.comonData.loginTime = new Date().getTime();
        this.saveData();
    },

    /** 设置登录成功 */
    loginFinish: function (data) {
        console.log('CommonInfo loginFinish: ', data);
        this.loginUrl = data.game_gate;
        this.userInfo.userid = data.user_id;
        this.userRegisted = data.user_state === 1;
    },

    /** 更新玩家信息 */
    updatePlayer: function (userid, data) {
        let player = this.getPlayerByID(userid);

        CommonUtil.copyProp(data, player, ['errcode', 'charid']);
        return player;
    },

    /** 保存数据 */
    saveData: function () {
        console.log('saveData:', this.comonData);
        cc.sys.localStorage.setItem(DATA_KEY, JSON.stringify(this.comonData));
    },

    // /** 无效数据 */
    // invalid: function () {
    //     return this.comonData === null;
    // },

    getRecentHeads: function () {
        return this.comonData.recentHeads;
    },

    setRecentHeads: function (value) {
        console.log('setRecentHeads:' + value);
        this.comonData.recentHeads.splice(0, 0, value);
        this.comonData.recentHeads.pop();
        this.saveData();
    },

    getTeched: function () {
        return this.comonData.teched;
    },

    setTeched: function (flag) {
        this.comonData.teched = flag;
        this.saveData();
    },

    getAutoRevive: function () {
        return this.comonData.autoRevive;
    },

    setAutoRevive: function (flag) {
        this.comonData.autoRevive = flag;
        this.saveData();
    },

    validateCacheUserInfo: function () {
        console.log('loginTime:', this.comonData.loginTime);
        return this.comonData && this.comonData.loginTime &&
            this.comonData.cacheUserInfo &&
            (this.comonData.loginTime + LOGIN_INVALID_TIME) > new Date().getTime();
    },

    doCacheLogin: function () {
        console.log('doCacheLogin:', this.comonData);
        let cacheUserInfo = this.comonData.cacheUserInfo;

        this.userRegisted = true;
        this.userInfo.nickname = cacheUserInfo.nickname;
        this.userInfo.headimgurl = cacheUserInfo.headimgurl;
        this.userInfo.sex = cacheUserInfo.sex;
        this.userInfo.province = cacheUserInfo.province;
        this.userInfo.city = cacheUserInfo.city;
    },

    checkRegisted: function (finishCb) {
        if (this.userRegisted) return true;

        require('Alert').show(null, REQUIRE_REGIST_STR, null,
            function () {
                require('GameConfig').userProto.login(finishCb);
            }, this
        );
    },

    // /** 是否在游戏中 */
    // inGameScene: function () {
    //     return this.sceneState === 2;
    // },

    // /** 是否在回放中 */
    // inRecordScene: function () {
    //     return this.sceneState === 3;
    // },

    // /** 改变玩家分数 */
    // changeUserScore: function (chairID, delta) {
    //     this.players[chairID].score += delta;

    //     let score = this.players[chairID].score;

    //     if (this.selfChair(chairID)) {
    //         this.userInfo.score = score;
    //     }

    //     return score;
    // },

    // /** 通过位置获取玩家性别 */
    // getSexByPos: function (pos) {
    //     let chairID = this.pos2Seat(pos), 
    //         sex = 1;

    //     if (chairID >= 0 && this.players && 
    //             this.players.length > chairID &&
    //             this.players[chairID].sex &&
    //             this.players[chairID].sex >= 1)
    //         sex = this.players[chairID].sex;
    //     return sex;
    // },

    /** 获得玩家信息（座位） */
    getPlayerByChair: function (chairID) {
        return this.players[chairID];
    },

    /** 获得玩家信息（id） */
    getPlayerByID: function (id) {
        let result = null, len = this.seatNum, player;

        for (let i = 0; i < len; ++i) {
            player = this.players[i];

            if (!player) continue;

            if (player.userid === id) {
                result = player;
                break;
            }
        }

        return result;
    },

    // /** 是否房间满员 */
    // full: function () {
    //     return this.players.length === this.seatNum;
    // },

    // /** 是否是自己（座位） */
    // selfChair: function (seat) {
    //     return this.chairID() === seat;
    // },

    /** 是否是自己（id） */
    self: function (id) {
        return this.userID() === id;
    },

    // /** 自己的桌号 */
    // tableID: function () {
    //     if (!this.userInfo) return -1;

    //     return this.userInfo.tableID;
    // },

    /** 自己的座位号 */
    chairID: function () {
        if (!this.userInfo) return -1;

        return this.userInfo.chairID;
    },

    // /** 自己的unionID */
    // unionID: function () {
    //     if (!this.userInfo) return '';

    //     return this.userInfo.unionid;
    // },

    /** 自己的id */
    userID: function () {
        if (!this.userInfo) return 0;

        return this.userInfo.userid;
    },

    nickName: function () {
        if (!this.userInfo) return '';

        return this.userInfo.nickname;
    },

    city: function () {
        if (!this.userInfo) return '';

        return this.userInfo.city;
    },

    province: function () {
        if (!this.userInfo) return '';

        return this.userInfo.province;
    },

    sex: function () {
        if (!this.userInfo) return 0;

        return this.userInfo.sex;
    },

    /** 绝对座位转换相对座位 */
    seat2Pos: function (seatNum) {
        if (seatNum < 0 || seatNum === null || seatNum === undefined ||
            this.seatNum <= 0 || seatNum >= this.seatNum)
            return -1;

        let result = (seatNum - this.chairID() +
            this.seatNum) % this.seatNum;

        if (result === null || result === undefined || isNaN(result) ||
            result >= this.seatNum || result < 0)
            result = -1;

        return result;
    },

    /** 相对座位转换绝对座位 */
    pos2Seat: function (pos) {
        if (pos < 0 || pos === null || pos === undefined || this.seatNum <= 0)
            return -1;

        let result = (this.chairID() + pos +
            this.seatNum) % this.seatNum;

        if (result === null || result === undefined || isNaN(result) ||
            result >= this.seatNum || result < 0)
            result = -1;

        return result;
    },

    // /** 玩家类型转换为userinfo信息 */
    // player2UserInfo: function (player) {
    //     if (!player) return null;

    //     return {
    //         isReady: player.state === 3,
    //         isDisconnected: player.state === 6,
    //         userName: player.nickname,
    //         score: player.score,
    //         userID: player.userid,
    //         headUrl: player.headimgurl,
    //         ip: player.ip
    //     };
    // },

    // /** 清除游戏信息 */
    // clearData: function () {
    //     this.players.length = 0;
    //     this.roomNum = 0;
    //     this.maxValue = -1;
    //     this.gameMediator = null;
    //     this.recordData = null;
    // },

    // isReady: function () {
    //     return this.userInfo.state === 3;
    // },

    // isDisconnected: function () {
    //     return this.userInfo.state === 6;
    // },

    isPlaying: function () {
        return this.userInfo.state === 5;
    },

    setUserState: function (state) {
        this.userInfo.state = state;

        if (this.chairID() >= 0)
            this.players[this.chairID()].state = state;
    },

    // /** 进入游戏 */
    // enterGame: function () {
    //     let len = this.seatNum;

    //     for (let i = 0; i < len; ++i) {
    //         this.players[i] = null;
    //     }
    // },

    // /** 设置回放玩家 */
    // setRecordPlayers: function () {
    //     let raw, len = this.recordData.kPlayersLen,
    //         self, player, i;

    //     this.seatNum = len;
    //     this.enterGame();

    //     for (i = 0; i < len; ++i) {
    //         raw = this.recordData.kPlayers[i];

    //         if (i === this.recorderChairID) {
    //             //先更新chairID计算正确的pos
    //             this.userInfo.chairID = i;
    //             break;
    //         }
    //     }

    //     for (i = 0; i < len; ++i) {
    //         raw = this.recordData.kPlayers[i];
    //         player = {};
    //         player.userid = raw.dwUserID;
    //         player.chairID = i;
    //         player.headimgurl = AppInfo.appCheck ? '' : raw.kHead;
    //         player.sex = raw.cbGender;
    //         player.pos = this.seat2Pos(player.chairID);
    //         player.score = raw.lGrade;
    //         player.nickname = AppInfo.appCheck ? '游客' : SensitiveUtil.filter(raw.kNickName);
    //         this.players[i] = player;
    //     }
    // },

    // /** 玩家是否已经在玩家列表 */
    // playerEntered: function (chairID) {
    //     if (chairID < 0 || chairID >= this.seatNum)
    //         return false;

    //     return this.players[chairID];
    // },

    // /** 玩家离开 */
    // playerLeave: function (chairID) {
    //     this.players[chairID] = null;
    // },

    // /** 当yy玩家信息获得后 */
    // yyGetInfo: function (data) {
    //     data = JSON.parse(data);

    //     let player = this.players[data.extra],
    //         arr = data.location.split('#');

    //     player.location = arr[0];
    //     player.longitude = arr[1];
    //     player.latitude = arr[2];

    //     if (parseInt(data.extra) === this.chairID()) {
    //         player.distance = 0;
    //         this.userInfo.location = player.location;
    //         this.userInfo.longitude = player.longitude;
    //         this.userInfo.latitude = player.latitude;
    //         this.userInfo.distance = 0;
    //     }
    // },

    // /** 玩家地理信息获得后 */
    // getLocation: function (location, chairID) {
    //     let player = this.players[chairID],
    //         arr = location.split('#');

    //     if (player.location !== undefined) {
    //         //已经和该玩家互推消息
    //         return null;
    //     }

    //     player.location = arr[0];
    //     player.longitude = arr[1];
    //     player.latitude = arr[2];

    //     if (this.selfChair(chairID)) {
    //         player.distance = 0;
    //         this.userInfo.location = player.location;
    //         this.userInfo.longitude = player.longitude;
    //         this.userInfo.latitude = player.latitude;
    //         this.userInfo.distance = 0;
    //     }

    //     return player.location;
    // },

    // /** 测算玩家距离 */
    // calDistance: function () {
    //     if (this.userInfo.distance === undefined) return;

    //     let len = this.seatNum - 1;

    //     for (let i = this.chairID() + 1, count = 0; count < len; ++i, ++count) {
    //         if (i === this.seatNum) i = 0;

    //         this.calOneDis(i);
    //     }
    // },

    // /** 测算单个玩家距离 */
    // calOneDis: function (chairID) {
    //     if (this.userInfo.distance === undefined) return;
    //     if (this.players[chairID].longitude === undefined ||
    //         this.players[chairID].latitude === undefined)
    //         return;

    //     this.players[chairID].distance = require('MathUtil').getGeoDistance(
    //         this.userInfo.longitude, this.userInfo.latitude,
    //         this.players[chairID].longitude, 
    //         this.players[chairID].latitude
    //     );

    //     return {
    //         pos: this.seat2Pos(chairID),
    //         distance: this.players[chairID].distance
    //     };
    // },

    // /** 获取同IP玩家 */
    // getIPResult: function () {
    //     let result = [];

    //     for (let i = 0; i < this.players.length - 1; ++i) {
    //         for (let j = i + 1; j < this.players.length; ++j) {
    //             if (CommonUtil.sameIP(this.players[i].ip, this.players[j].ip)) {
    //                 if (result.indexOf(this.players[i]) === -1)
    //                     result[result.length] = this.players[i];

    //                 if (result.indexOf(this.players[j]) === -1)
    //                     result[result.length] = this.players[j];
    //             }
    //         }
    //     }

    //     return result;
    // },

    setGameUrl: function (raw) {
        this.gameUrl = raw.ip;//'ws://' + raw.ip + ':' + raw.port;
    },

    getAnother: function () {
        return this.players[this.chairID() === 0 ? 1 : 0];
    },

    //--------------------------------------------------------------

    MatchSuccessS: function (raw) {
        let ids = raw.charids,
            len, i,
            player, self, other;

        this.setGameUrl(raw);
        this.record = raw.record;
        len = this.seatNum = ids.length;
        this.players.length = 0;

        for (i = 0; i < len; ++i) {
            player = {};
            player.userid = ids[i];

            if (!AppInfo.wx) {
                player.nickname = player.userid + '';
            }

            player.chairID = i;
            self = this.self(player.userid);

            if (self) {
                this.userInfo.chairID = player.chairID;
            }

            this.players[i] = player;
        }

        for (i = 0; i < len; ++i) {
            player = this.players[i];
            player.pos = this.seat2Pos(player.chairID);
            self = this.self(player.userid);

            if (self) {
                CommonUtil.copyProp(player, this.userInfo);
                CommonUtil.copyProp(this.userInfo, player);
            }
        }

    },

    StartGameS: function (raw) {
        let i, len,
            rawPlayer, player,
            self;

        this.seatNum = 2;

        for (i = 0; i < 2; ++i) {
            player = {};
            rawPlayer = raw.infos[i];
            player.userid = rawPlayer.charid;

            if (!AppInfo.wx) {
                player.nickname = player.userid + '';
            }

            player.chairID = i;
            self = this.self(player.userid);

            if (self) {
                this.userInfo.chairID = player.chairID;
            }

            this.players[i] = player;
        }

        for (i = 0; i < 2; ++i) {
            player = this.players[i];
            player.pos = this.seat2Pos(player.chairID);
            self = this.self(player.userid);

            if (self) {
                CommonUtil.copyProp(player, this.userInfo);
                CommonUtil.copyProp(this.userInfo, player);
            }
        }
    },

};

module.exports = CommonInfo;